"""
统计数据 API
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from datetime import datetime, timedelta, timezone
from typing import Optional

from  core.database import get_db
from  api.deps import get_current_active_doctor
from  models.doctor import Doctor
from  models.patient import Patient
from  models.medical_record import MedicalRecord
from  models.template import Template
from  schemas.common import success_response

router = APIRouter()


@router.get("/overview", response_model=dict, summary="获取统计概览")
async def get_statistics_overview(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
) -> dict:
    """
    获取系统统计概览
    
    返回：
    - 医生总数
    - 患者总数
    - 病历总数
    - 模板总数
    """
    # 统计医生数量
    result = await db.execute(
        select(func.count(Doctor.id)).where(Doctor.status == 1)
    )
    doctor_count = result.scalar() or 0
    
    # 统计患者数量
    result = await db.execute(
        select(func.count(Patient.id)).where(Patient.status == 1)
    )
    patient_count = result.scalar() or 0
    
    # 统计病历数量
    result = await db.execute(
        select(func.count(MedicalRecord.id)).where(MedicalRecord.status == 1)
    )
    record_count = result.scalar() or 0
    
    # 统计模板数量
    result = await db.execute(
        select(func.count(Template.id)).where(Template.is_active == True)
    )
    template_count = result.scalar() or 0
    
    return success_response(
        data={
            "doctor_count": doctor_count,
            "patient_count": patient_count,
            "record_count": record_count,
            "template_count": template_count
        },
        message="获取成功"
    )


@router.get("/my-statistics", response_model=dict, summary="获取我的统计数据")
async def get_my_statistics(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
) -> dict:
    """
    获取当前医生的统计数据
    
    返回：
    - 我的患者数量
    - 我的病历数量（最近7天、30天）
    """
    # 我的患者数量
    result = await db.execute(
        select(func.count(Patient.id))
        .where(Patient.doctor_id == current_doctor.id)
        .where(Patient.status == 1)
    )
    my_patient_count = result.scalar() or 0
    
    # 我的患者的病历数量
    result = await db.execute(
        select(func.count(MedicalRecord.id))
        .join(Patient, MedicalRecord.patient_id == Patient.id)
        .where(Patient.doctor_id == current_doctor.id)
        .where(MedicalRecord.status == 1)
    )
    my_record_count = result.scalar() or 0
    
    # 最近7天的病历数量
    seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
    result = await db.execute(
        select(func.count(MedicalRecord.id))
        .join(Patient, MedicalRecord.patient_id == Patient.id)
        .where(Patient.doctor_id == current_doctor.id)
        .where(MedicalRecord.status == 1)
        .where(MedicalRecord.created_at >= seven_days_ago)
    )
    recent_7_days = result.scalar() or 0
    
    # 最近30天的病历数量
    thirty_days_ago = datetime.now(timezone.utc) - timedelta(days=30)
    result = await db.execute(
        select(func.count(MedicalRecord.id))
        .join(Patient, MedicalRecord.patient_id == Patient.id)
        .where(Patient.doctor_id == current_doctor.id)
        .where(MedicalRecord.status == 1)
        .where(MedicalRecord.created_at >= thirty_days_ago)
    )
    recent_30_days = result.scalar() or 0
    
    return success_response(
        data={
            "my_patient_count": my_patient_count,
            "my_record_count": my_record_count,
            "recent_7_days_records": recent_7_days,
            "recent_30_days_records": recent_30_days
        },
        message="获取成功"
    )


@router.get("/patient-statistics", response_model=dict, summary="患者统计")
async def get_patient_statistics(
    group_by: str = Query("gender", description="分组依据：gender(性别), age(年龄段)"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
) -> dict:
    """
    患者统计数据
    
    - 按性别统计
    - 按年龄段统计
    """
    if group_by == "gender":
        # 按性别统计
        result = await db.execute(
            select(Patient.gender, func.count(Patient.id))
            .where(Patient.status == 1)
            .group_by(Patient.gender)
        )
        stats = [{"gender": row[0] or "未知", "count": row[1]} for row in result.all()]
        
        return success_response(
            data={"statistics": stats, "group_by": "gender"},
            message="获取成功"
        )
    
    elif group_by == "age":
        # 按年龄段统计（0-18, 19-35, 36-50, 51-65, 66+）
        result = await db.execute(
            select(Patient).where(Patient.status == 1)
        )
        patients = result.scalars().all()
        
        age_groups = {
            "0-18": 0,
            "19-35": 0,
            "36-50": 0,
            "51-65": 0,
            "66+": 0,
            "未知": 0
        }
        
        for patient in patients:
            age = patient.age
            if age is None:
                age_groups["未知"] += 1
            elif age <= 18:
                age_groups["0-18"] += 1
            elif age <= 35:
                age_groups["19-35"] += 1
            elif age <= 50:
                age_groups["36-50"] += 1
            elif age <= 65:
                age_groups["51-65"] += 1
            else:
                age_groups["66+"] += 1
        
        stats = [{"age_group": k, "count": v} for k, v in age_groups.items()]
        
        return success_response(
            data={"statistics": stats, "group_by": "age"},
            message="获取成功"
        )
    
    else:
        return success_response(
            data={"statistics": [], "group_by": group_by},
            message="不支持的分组方式"
        )


@router.get("/disease-statistics", response_model=dict, summary="疾病统计")
async def get_disease_statistics(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
) -> dict:
    """
    疾病统计数据
    
    统计各种疾病的患者数量
    """
    result = await db.execute(
        select(Patient).where(Patient.status == 1)
    )
    patients = result.scalars().all()
    
    disease_stats = {
        "diabetes": 0,          # 糖尿病
        "hypertension": 0,      # 高血压
        "hyperlipidemia": 0,    # 高血脂
        "stroke_history": 0,    # 卒中史
        "heart_disease": 0,     # 心脏病
        "atrial_fibrillation": 0,  # 房颤
        "sleep_apnea": 0        # 睡眠呼吸暂停
    }
    
    for patient in patients:
        if patient.diabetes:
            disease_stats["diabetes"] += 1
        if patient.hypertension:
            disease_stats["hypertension"] += 1
        if patient.hyperlipidemia:
            disease_stats["hyperlipidemia"] += 1
        if patient.stroke_history:
            disease_stats["stroke_history"] += 1
        if patient.heart_disease:
            disease_stats["heart_disease"] += 1
        if patient.atrial_fibrillation:
            disease_stats["atrial_fibrillation"] += 1
        if patient.sleep_apnea:
            disease_stats["sleep_apnea"] += 1
    
    return success_response(
        data=disease_stats,
        message="获取成功"
    )


@router.get("/summary", response_model=dict, summary="获取指定时间段内的汇总数据")
async def get_summary_by_date(
    startTime: str = Query(..., description="开始时间，格式：YYYY-MM-DD"),
    endTime: str = Query(..., description="结束时间，格式：YYYY-MM-DD"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
) -> dict:
    """
    获取指定时间段内的汇总数据
    
    Args:
        startTime: 开始时间，格式：YYYY-MM-DD
        endTime: 结束时间，格式：YYYY-MM-DD
        
    Returns:
        dates: 日期列表
        patients: 每日患者数量列表
        records: 每日病历数量列表
    """
    try:
        # 转换时间格式
        start_date = datetime.strptime(startTime, '%Y-%m-%d')
        end_date = datetime.strptime(endTime, '%Y-%m-%d') + timedelta(days=1)  # 包含结束日期当天
        
        # 生成日期列表
        dates = []
        current_date = start_date
        while current_date < end_date:
            dates.append(current_date.strftime('%Y-%m-%d'))
            current_date += timedelta(days=1)
        
        # 初始化结果数组
        patients_count = [0] * len(dates)
        records_count = [0] * len(dates)
        
        # 获取当前医生的患者数据（按updated_at统计）
        result = await db.execute(
            select(Patient).where(
                Patient.doctor_id == current_doctor.id,
                Patient.status == 1,
                Patient.updated_at >= start_date,
                Patient.updated_at < end_date
            )
        )
        patients = result.scalars().all()
        
        # 统计每日患者数量
        for patient in patients:
            if patient.updated_at:
                patient_date = patient.updated_at.strftime('%Y-%m-%d')
                if patient_date in dates:
                    index = dates.index(patient_date)
                    patients_count[index] += 1
        
        # 获取病历数据（需要通过患者关联到当前医生）
        result = await db.execute(
            select(MedicalRecord)
            .join(Patient, MedicalRecord.patient_id == Patient.id)
            .where(
                Patient.doctor_id == current_doctor.id,
                MedicalRecord.status == 1,
                MedicalRecord.updated_at >= start_date,
                MedicalRecord.updated_at < end_date
            )
        )
        records = result.scalars().all()
        
        # 统计每日病历数量
        for record in records:
            if record.updated_at:
                record_date = record.updated_at.strftime('%Y-%m-%d')
                if record_date in dates:
                    index = dates.index(record_date)
                    records_count[index] += 1
        
        return success_response(
            data={
                'dates': dates,
                'patients': patients_count,
                'records': records_count
            },
            message='获取汇总数据成功'
        )
        
    except ValueError:
        return {
            'message': '时间格式错误',
            'code': 1
        }
    except Exception as e:
        return {
            'message': f'服务器错误: {str(e)}',
            'code': 1
        }

